<?php

namespace App\Http\Services;

use App\Http\Model\ContentCheck;
use App\Http\Model\Family;
use App\Http\Model\Hint;
use App\Http\Model\Origami\UserOrigami;
use App\Http\Model\Room;
use App\Http\Model\RoomImageCheck;
use App\Http\Model\Trends;
use App\Http\Model\Union;
use App\Http\Model\UnionUser;
use App\Http\Model\User;
use App\Lib\oss;
use App\Lib\Publisher;
// use App\Lib\Shumei;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class ContentCheckServices extends CommonServices
{
    protected $contentCheckModel;
    protected $userModel;
    protected $roomModel;
    protected $trendModel;
    protected $roomImgCheckModel;
    protected $unionModel;
    protected $unionUserModel;
    protected $familyModel;
    protected $shumeiFilterConf;
    protected $userService;
    protected $prepare_img_key = 'USER:HEAD:PREOARE:';//用户预备头像 USER:HEAD:PREOARE:{$userId}=>{string}

    public function __construct()
    {
        $this->contentCheckModel = new ContentCheck();
        $this->userModel = new User();
        $this->roomModel = new Room();
        $this->trendModel = new Trends();
        $this->roomImgCheckModel = new RoomImageCheck();
        $this->unionModel = new Union();
        $this->unionUserModel = new UnionUser();
        $this->familyModel = new Family();
        $this->userService = new UserServices();
        // $this->shumeiFilterConf = config('shumei_filter');
    }

    /**
     * 检测用户信息
     * @param $data
     * @return array
     */
    public function checkUserContent($data){

        $userKey = ["nickname", "sign", "voice", "images", "user_id", "voice_time", "user_uid"];
        $checkKeys = ["nickname", "sign", "voice", "images"];
        $result = [];

        //获取用户信息
        $userData = $this->userModel->get_current_user();
        $userData = array_intersect_key($userData, array_flip($userKey));

        // //交友数美音频校验
        // if(!empty($data['voice'])){
        //     $voiceInfo = parse_url($data['voice']);
        //     $data['voice'] = (isset($voiceInfo['path']) && isset($voiceInfo['host'])) ? $voiceInfo['path'] : "";
        //     $check_voice = build_url($data['voice']);
        //     $res = $this->userService->checkAudio($check_voice,$userData['user_id']);
        //     $res = json_decode($res ,true);
        //     if($res['code'] == 1100 && $res['detail']['riskLevel'] != 'PASS'){
        //         return ['code'=>Hint::ERR_NORMAL,'msg'=>'您的内容不合规，请重新填写，如多次不合格将封禁您的账号'];
        //     }
        // }
        //查看传递过来的图片中是否包含预备头像,若没有则清空预备数据
        $comparArr = explode(',',$data['images']);
        $key = array_search($data['prepare_img'],$comparArr);
        if(!$key){
            Redis::del($this->prepare_img_key.$userData['user_id']);
            $data['prepare_img'] = '';
        }
        //添加图片审核
        if (isset($data['images']) && !empty($data['images'])) {
            $images = @array_diff($data['images'], $userData["images"]);
            // if ($images) {
            //     //清除之前提交的图片数据
            //     foreach ($images as $key => $value) {
            //         if (empty($value)){
            //             continue;
            //         }
            //         $this->contentCheckModel->pushImage($userData['user_id'], $value, 1);
            //     }
            // }
            $result['images'] = implode(",", $data['images']);
            //预设头像信息
            if(!empty($data['prepare_img'])){
                Redis::set($this->prepare_img_key.$userData['user_id'], $data['prepare_img']);
            }
        }


        //内容检测开关
        $contentCheckSwitch = $this->contentCheckModel->getContentCheckSwitch();
        if (!$contentCheckSwitch) {return $data;}

        //处理删除信息
        if (isset($data['voice']) && empty($voice['voice'])) {
            $this->contentCheckModel->delContentCheckByCheckObjAndDataId(6, $userData['user_id']);
        }

        //处理用户头像/相册
        if (isset($data['images'])) {
            $data['images'] = explode(",", $data['images']);
        }
        //获取用户需要审核数据
        $diffData = @array_diff($data, $userData);
        foreach ($diffData as $key => $value) {
            if (in_array($key, $checkKeys) && !empty($value)) {
                switch ($key) {
                    //用户昵称
                    case "nickname" :
                        $this->contentCheckModel->create($userData['user_id'], 1, $value, "用户" . $userData['user_uid'], $userData['user_id']);
                        if ($userData[$key] == "") {
                            $userData[$key] = "用户" . $userData['user_uid'];
                        }
                        break;
                    //用户签名
                    case "sign" :
                        $this->contentCheckModel->create($userData['user_id'], 2, $value,"这个人懒得写签名", $userData['user_id']);
                        break;
                    //用户语音
                    case "voice" :
                        $contentAdd['voice_time'] = $data['voice_time'] ?? 0;
                        $contentAdd['old_voice_time'] = $userData['voice_time'] ?? 0;
                        $this->contentCheckModel->create($userData['user_id'], 6, $value, $userData[$key], $userData['user_id'], json_encode($contentAdd));
                        break;
                }
                $result[$key] = isset($userData[$key]) ? $userData[$key] : "";
            }
        }


        //处理图片
        if (isset($data['images']) && !empty($data['images'])) {

            $images = @array_diff($data['images'], $userData["images"]);

            //已经提交审核的元素
            $checks = $this->contentCheckModel->getContentCheckListByUserIdAndCheckObj($userData['user_id'], [8]);
            $subImages = [];
            if(!empty($checks)){
                $checksImages = array_column($checks,'content');
                $subImages = @array_diff($checksImages,$images);
                $images = @array_diff($images,$checksImages);
            }

            if ($images) {
                //清除之前提交的图片数据
//                $this->contentCheckModel->delContentCheckByCheckObjAndUserId(8, $userData['user_id']);
                foreach ($images as $key => $value) {
                    if (empty($value)){
                        continue;
                    }

                    if (strpos($value, 'portrait/') !== false) {
                        continue; //系统头像不审核
                    }

                    $this->contentCheckModel->pushImage($userData['user_id'], $value, 1);
                    $this->contentCheckModel->create($userData['user_id'], 8, $value, "", $userData['user_id'], $key);
                }
            }

            //删除图片
            if ($subImages) {
                $this->contentCheckModel->delContentCheckByContents($userData['user_id'], 8, $subImages);
            }

            $result['images'] = implode(",", $data['images']);
        }

        return $result;
    }



    /**
     * 检测房间信息信息
     * @param $data
     * @return array
     */
    public function checkRoomContent($data){

        $roomKey = ["name", "notice", "desc", "image", "room_id"];
        $checkKeys = ["name", "notice", "desc", "image"];
        $result = [];

        //获取房间信息
        $roomData = $this->roomModel->get_room($data['room_id']);
        if (!$roomData) {
            return false;
        }
        $roomData = array_intersect_key($roomData, array_flip($roomKey));

        //获取用户信息
        $userData = $this->userModel->get_current_user();


        //添加图片审核
        $diffData = @array_diff($data, $roomData);
        foreach ($diffData as $key => $value) {
            if (in_array($key, $checkKeys)) {
                if($key == "image"){
                    $this->contentCheckModel->pushImage($userData['user_id'], $value, 2);
                }
            }
        }

        //内容检测开关
        $contentCheckSwitch = $this->contentCheckModel->getContentCheckSwitch();
        if (!$contentCheckSwitch) {return $data;}


        //获取用户需要审核数据
        $diffData = @array_diff($data, $roomData);
        foreach ($diffData as $key => $value) {
            if (in_array($key, $checkKeys)) {
                switch ($key) {
                    //房间标题
                    case "name" :
                        $this->contentCheckModel->create($userData['user_id'], 3, $value, "聊天室", $roomData['room_id']);
                        break;
                    //房间公告
                    case "notice" :
                        $this->contentCheckModel->create($userData['user_id'], 4, $value, "欢迎来到聊天室", $roomData['room_id']);
                        break;
                    //房间描述
                    case "desc" :
                        $this->contentCheckModel->create($userData['user_id'], 5, $value, "聊天室", $roomData['room_id']);
                        break;
                    //房间封面
                    case "image" :
                        $this->contentCheckModel->create($userData['user_id'], 7, $value, "", $roomData['room_id']);
                        break;
                }
            }
        }

        return $roomData;
    }




    /**
     * 检测动态信息
     * @param $data
     * @return bool
     */
    public function checkTrendContent($data, $imageUrls){
        //获取用户信息
        $userData = $this->userModel->get_current_user();

        //图片检测
        foreach ($imageUrls as $k => $v) {
            $this->contentCheckModel->pushImage($userData['user_id'], $v, 3);
        }

        //内容检测开关
        $contentCheckSwitch = $this->contentCheckModel->getContentCheckSwitch();
        if (!$contentCheckSwitch) {return $data;}

        $this->contentCheckModel->create($userData['user_id'], 10, "", "", $data['content_id']);
        return true;
    }


    /**
     * 检测动态评论信息
     * @param $data
     * @return bool
     */
    public function checkTrendCommentContent($data){
        //内容检测开关
        $contentCheckSwitch = $this->contentCheckModel->getContentCheckSwitch();
        if (!$contentCheckSwitch) {return $data;}

        //获取用户信息
        $userData = $this->userModel->get_current_user();

        $comment['comment_text'] = $data['comment_text'];
        $comment['comment_voice'] = $data['comment_voice'];

        //处理文字评论检测
        if (isset($comment['comment_text']) || isset($comment['comment_voice'])) {
            $this->contentCheckModel->create($userData['user_id'], 11, json_encode($comment), "", $data['comment_id'], "", $data['content_id']);
        }

        return true;
    }

    /**
     * 检测动态评论回复信息
     * @param $data
     * @return bool
     */
    public function checkTrendCommentReplyContent($data){
        //内容检测开关
        $contentCheckSwitch = $this->contentCheckModel->getContentCheckSwitch();
        if (!$contentCheckSwitch) {
            return $data;
        }

        //获取用户信息
        $userData = $this->userModel->get_current_user();

        $comment['comment_text'] = $data['reply_content'];
        $comment['comment_voice'] = $data['reply_voice'];

        //处理文字评论检测
        if (isset($comment['comment_text']) || isset($comment['comment_voice'])) {
            $this->contentCheckModel->create($userData['user_id'], 12, json_encode($comment), "", $data['reply_id'], "", $data['content_id']);
        }

        return true;
    }

    /**
     * CMS审核语音内容
     * */
    public function checkAudit()
    {
        $code = Hint::SUCCESS;
        $msg = Hint::getErrCodeMsg($code);
        $data = [];
        do {
            $this->I('id', 'ID', 'string', true, 'ID数据错误');
            $this->I('status', '审核状态', 'int', true, '审核状态');// 0=待审核，1=通过 2=驳回
            $this->I('type', '审核类型', 'int', true, '审核类型');//1-初审 2-复审
            $this->I('opt_id', '审核人ID', 'int', true, '审核人ID');

            $variables = [];
            $checkParams = $this->check($this->requestData, $variables); //校验数据
            extract($checkParams);
            extract($variables); //数组参数化
            if ($code !== Hint::SUCCESS) {
                break;
            }

            $ids = explode(",", $this->requestData['id']);
            $status = $this->requestData['status'];
            $type = $this->requestData['type'];
            $opt_id = $this->requestData['opt_id'];

            //查看审核内容
            $contentCheckData = $this->contentCheckModel->getByIds($ids);
            foreach ($contentCheckData as $key => $value) {
                //审核通过业务相关处理
                if ($type == 1 || ($type == 2 && $status == 2)) {
                    $this->handleContentCheck($type, $status, $value);
                }
                $this->contentCheckModel->updateContentCheck($value['id'], $status, $type, $opt_id, $value['user_id']);
                $data[$key]['user_id'] = $value['user_id'];
                $data[$key]['key'] = $value['check_obj'];
                $data[$key]['content'] = $status  == 1 ? $value['content'] : $value['old_content'];
                $data[$key]['data_id'] = $value['data_id'];
                $data[$key]['other_content_id'] = $value['content_id'];
                $data[$key]['new_content'] = $value['content']; //上面的content字段被old_content复写了，真坑爹
            }

        } while (false);

        return compact('code', 'msg', 'data');
    }

    //审核通过处理
    public function handleContentCheck($type, $status, $data)
    {
        switch ($data['check_obj']) {
            case 1 :
            case 2 :
            case 6 :
            case 8 :
                $this->handleUserContent($type, $status, $data['data_id'], $data['check_obj'], $data);
                break;
            case 3 :
            case 4 :
            case 5 :
            case 7 :
                $this->handleRoomContent($type, $status, $data['data_id'], $data['check_obj'], $data);
                break;
            case 9 :
                break;
            case 10 :
                $this->handleThrendContent($type, $status, $data['data_id'], $data['check_obj'], $data);
                break;
            case 11 :
                $this->handleThrendCommentContent($type, $status, $data['data_id'], $data['check_obj'], $data);
                break;
            case 12 :
                $this->handleThrendCommentReplyContent($status, $data['data_id'], $data['user_id']);
                break;
            case 13:
                $this->handleRoomMsgImageStatus($status ,$data['content_id']);
                break;
            case 14:
                $this->handleUnionName($status ,$data['data_id'],$data);
                break;
            case 15:
                $this->handleUnionDeclaration($status ,$data['data_id']);
                break;
            case 16:
                $this->handleUnionNotice($status ,$data['content_id']);
                break;
            case 17:
                $this->handleUnionVest($status ,$data['data_id'],$data);
                break;
            case 18:
                $this->handleFamilyName($status ,$data['data_id'],$data);
                break;
            case 19:
                $this->handleFamilyDeclaration($status ,$data['data_id']);
                break;
            case 20:
                $this->handleFamilyPortrait($status ,$data['data_id']);
                break;
            case 21 :
                break;
            case 22 :
                break;
            case 23 :
                break;
            case 24 :
                break;
            case 25 :
                break;
            case 26 ://折纸
                $this->handleOrigamiContent($status, $data['data_id']);
                break;
        }
    }

    /**
     * 更新折纸状态，清除缓存
     *
     * Created at 2021/10/18 15:39
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @param int $status //1=通过 2=驳回
     * @param int $dataId
     */
    public function handleOrigamiContent($status, $dataId)
    {
        $userOrigami = new UserOrigami();
        $userData = $userOrigami->getFirstByid($dataId);
        $auditStatus = $status == 1 ? UserOrigami::AUDIT_STATUS_OF_AUDIT_SUCCESS : UserOrigami::AUDIT_STATUS_OF_AUDIT_FAIL;
        $userOrigami->checkUserOrigami($dataId, $auditStatus);
        $userOrigami->clearAndResetCache($userData['user_id']);
    }

    public function handleUserContent($type, $status, $userId, $checkObj, $data)
    {
        $content = ($status == 1) ? $data['content'] : $data['old_content'];
        $content_add = $data['content_add'];
        if ($checkObj == 1 && $content) {
            $this->userModel->edit($userId, "", $content, "", "", "", "", "", "", "");
        }

        if ($checkObj == 2 && $content) {
            $this->userModel->edit($userId, "", "", "", "", "", "", "", "", $content);
        }

        if ($checkObj == 6) {
            $voiceTimeContent = json_decode($data['content_add'], true);
            $voice_time = ($status == 1) ? $voiceTimeContent['voice_time'] : $voiceTimeContent['old_voice_time'];
            $this->userModel->edit($userId, "", "", "", "", "", "", "", "", "", $content, $voice_time);
        }

        if ($checkObj == 8) {
            $userData = $this->userModel->get_user($userId);
            if ($userData && isset($userData['images'])) {
                $images = $userData['images'];
//                if (empty($content_add) && $content_add == "") {
//                    $images = array_merge($images, $content);
//                }else{
//                    $index = intval($content_add);
//                    $images[$index] = $content;
//                }
                //审核通过后查看有预备缓存中是否有数据,若相等则默认成头像
                if ($status == 1) {
                    $prepare_img = Redis::get($this->prepare_img_key.$userId);
                    if($prepare_img == $content && !empty($prepare_img)){
                        array_unshift($images,$content);
                        //驳回删除预备缓存
                        Redis::del($this->prepare_img_key.$userId);
                    }  
                }
                
                if ($status == 2) {
                    $key = array_search($data['content'], $images);
                    if ($key !== false) {
                        array_splice($images, $key, 1);
                    }
                    //驳回删除预备缓存
                    Redis::del($this->prepare_img_key.$userId);
                }
                $images = array_unique($images);
                $images = implode(",", array_values($images));
                if (empty($images)) {
                    $images = "album/default.png";
                }

                if ($images && !empty($images)) {
                    $this->userModel->edit($userId, "", "", "", "", $images, "", "", "", "");
                }
            }
        }
    }

    public function handleRoomContent($type, $status, $dataId, $checkObj, $data)
    {
        $content = ($status == 1) ? $data['content'] : $data['old_content'];

        if ($checkObj == 3) {
            $this->roomModel->set_name($dataId, $content, 1);
        }

        if ($checkObj == 4) {
            $this->roomModel->set_notice($dataId, $content);
        }

        if ($checkObj == 5) {
            $this->roomModel->set_desc($dataId, $content);
        }

        if ($checkObj == 7) {
            $this->roomModel->set_image($dataId, $content);
        }
    }


    public function handleThrendContent($type, $status, $userId, $checkObj, $data)
    {

    }

    public function handleThrendCommentContent($type, $status, $dataId, $checkObj, $data)
    {
        //通过处理
        if ($status == 1) {
            //更新评论状态

        }

        if ($status == 2) {
            $this->trendModel->trends_comment_del($dataId);
        }
    }

    public function handleThrendCommentReplyContent($status, $dataId, $userId)
    {
        //通过处理
        if ($status == 1) {
            //更新评论状态
        }

        if ($status == 2) {
            $this->trendModel->trends_reply_del($userId, $dataId);
        }
    }

    public function getContentCheckSwitch()
    {
        //内容检测开关
        return $this->contentCheckModel->getContentCheckSwitch();
    }


    /**更新房间发图片的状态
     * @param $status
     * @param $dataId
     * @param $userId
     */
    public function handleRoomMsgImageStatus($status, $content_id)
    {
        $this->roomImgCheckModel->CUDTable( array('status'=>$status),'update' ,$content_id);
	}

    /**
     * 循环处理图片检测
     */
    public function loopFilterImage(){
        // $sumei = new Shumei();
        // $oss = new oss();
        // for ($i = 0; $i < 10; $i++){
        //     $item = $this->contentCheckModel->popImage();
        //     if (empty($item)){
        //         return;
        //     }
        //     $result = $sumei->filterImage($item[0], $item[1]);
        //     if ($result >= 3){
        //         $urlData = parse_url($item[1]);
        //         $oss->frozenObject($urlData['path']);
        //     }
        //     $this->contentCheckModel->addImgSesult($item[1], $item[0], $item[2], $result);
        // }
    }

    //公会名称审核
    public function handleUnionName($status, $dataId,$data)
    {
        if($status ==2){
            if(!empty($data['old_content'])){
                $name = $data['old_content'];
            }else{
                $union = $this->unionModel->getUnionInfo($dataId);
                $name = '公会'.$union['uuid'];
            }
            $this->unionModel->setUnionInfo(array('union_id'=>$dataId,'name'=>$name) ,false);
        }
    }
    //公会宣言审核
    public function handleUnionDeclaration($status ,$dataId){
        if($status ==2){
            $union = $this->unionModel->getUnionInfo($dataId);
            $this->unionModel->setUnionInfo(array('union_id'=>$union['id'],'declaration'=>''));
        }
    }
    //公会公告审核
    public function handleUnionNotice($status,$content_id){
        if($status ==2){
            $this->unionModel->delNotice($content_id);
        }
    }
    //公会马甲审核
    public function handleUnionVest($status ,$dataId,$data){
        $union = $this->unionModel->getUnionInfo($dataId);
        //审核通过
        if($status ==1 && !empty($data['content'])){
            DB::beginTransaction();
            $this->unionModel->setUnionInfo(array('union_id'=>$union['id'],'vest'=>$data['content']));
            $users = $this->unionUserModel->getUserNum($dataId ,false);
            $user_ids = array_column($users ,'user_id');
            $this->userModel->batchSetUnionVestNew($user_ids,$data['content']);
            DB::commit();
        }
    }

    //家族名称审核
    public function handleFamilyName($status, $dataId,$data)
    {
        if($status ==2){
            if(!empty($data['old_content'])){
                $name = $data['old_content'];
            }else{
                $family = $this->familyModel->getFamilyInfoByFid($dataId);
                $name = '家族'.$family['uuid'];
            }
            $this->familyModel->setFamilyInfo(array('family_id'=>$dataId,'name'=>$name) ,false);
        }
    }
    //公会宣言审核
    public function handleFamilyDeclaration($status ,$dataId){
        if($status ==2){
            $this->familyModel->setFamilyInfo(array('family_id'=>$dataId,'declaration'=>''));
        }
    }
    //公会宣言审核
    public function handleFamilyPortrait($status ,$dataId){
        if($status ==2){
            if(!empty($data['old_content'])){
                $portrait = $data['old_content'];
            }else{
                $portrait = '/icon/default_icon.png';
            }
            $this->familyModel->setFamilyInfo(array('family_id'=>$dataId,'portrait'=>$portrait));
        }
    }

    /**
     * 交友折纸内容审核
     *
     * @param int $userId
     * @param int $recordId
     * @param string $content
     * @return bool
     */
    public function checkOrigamiContent(int $userId, int $recordId, string $content): bool
    {
        $this->contentCheckModel->create($userId, 26, $content, "", $recordId);
        return true;
    }

    /**
     * 文字机审测试
     */
    public function auditContentCeshi($content)
    {
        $url = $this->shumeiFilterConf['apihost'];
        $data['accessKey'] = $this->shumeiFilterConf['accessKey'];
        $data['type'] = $this->shumeiFilterConf['type'];
        $data['appId'] = $this->shumeiFilterConf['appId'];
        $data['organization'] = $this->shumeiFilterConf['organization'];
        $data['data'] = [
            "text" => $content,
            "tokenId" => (string)$this->getDataId()
        ];

        $ret_data = curl_request($url, $data, 'json', 'POST');
        $ret_data = json_decode($ret_data, true);
        if(!empty($ret_data['detail'])) {
            $ret_data['detail'] = empty($ret_data['detail']) ? $ret_data : json_decode($ret_data['detail'], true);
        }

        return $ret_data;
    }

    /**
     * 文字机审 不判断返回码,直接返回字符串
     */
    public function auditContent($userId, $content)
    {
        $result = [
            'content' => '',
            'third_result' => '',
        ];
        $result['content'] = $content;
        $result['third_result'] = json_encode(['机审审核未开启']);

        /*
        do {
            $url = $this->shumeiFilterConf['apihost'];
            $data['accessKey'] = $this->shumeiFilterConf['accessKey'];
            $data['type'] = $this->shumeiFilterConf['type'];
            $data['appId'] = $this->shumeiFilterConf['appId'];
            $data['organization'] = $this->shumeiFilterConf['organization'];
            $data['data'] = [
                "text" => $content,
                "tokenId" => (string)$this->getDataId()
            ];

            $ret_data = curl_request($url, $data, 'json', 'POST');
            $result['third_result'] = $ret_data;
            $ret_data = json_decode($ret_data, true);
            if(!empty($ret_data['detail'])) {
                $ret_data['detail'] = empty($ret_data['detail']) ? $ret_data : json_decode($ret_data['detail'], true);
                if(!empty($ret_data['detail']['contextText'])) {
                    if(!empty($ret_data['detail']['filteredText'])) {
                        $result['content'] = $ret_data['detail']['filteredText'];
                    }else{
                        $result['content'] = $ret_data['detail']['contextText'];
                    }
                }
            }
        } while (false);
        */

        return $result;
    }

    private function getDataId()
    {
        return uniqid();
    }

}
